<template>
  <ContentWrap>
    <fromTitle title="检验报告查询" :hasPermi="'qis:check-result:query'" :queryParams="queryParams" @search="getList" @reset="resetQuery" /> 

    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >


      <el-form-item label="甲方单位" prop="fistParty">
        <el-input
          v-model="queryParams.fistParty"
          placeholder="请输入甲方单位"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item  label="项目名称" prop="projectName">
        <el-input
          v-model="queryParams.projectName"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item  label="样品名称" prop="sampleName">
        <el-input
          v-model="queryParams.sampleName"
          placeholder="请输入样品名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
            <el-form-item  label="样品编号" prop="sampleNum">
        <el-input
          v-model="queryParams.sampleNum"
          placeholder="请输入样品编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item  label="承检机构" prop="orgName">
        <el-input
          v-model="queryParams.orgName"
          placeholder="请输入承检机构"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>


      
      <el-form-item label="抽样时间" prop="samplingStartDate">
        <el-date-picker
          v-model="queryParams.samplingStartDate1"
          value-format="YYYY-MM-DD"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>


      <el-form-item label="检验时间"  prop="checkStartTime1">
        <el-date-picker
          v-model="queryParams.checkStartTime1"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <!-- <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>

      </el-form-item> -->
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <div class="table-btn">
    <el-button type="info" @click="handleExport">导出</el-button>
    </div>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column width="55">
        <template #header>
          <span>选择</span>
        </template>
        <template #default="scope">
          <el-checkbox v-model="scope.row.selected" @change="handleSelect(scope.row)"/>
        </template>
      </el-table-column>
      <el-table-column label="项目名称" align="center" prop="projectName" />
      <el-table-column label="甲方单位" align="center" prop="fistParty" />
      <el-table-column label="样品名称" align="center" prop="sampleName" />
      <el-table-column label="样品编号" align="center" prop="sampleNum" />
      <el-table-column label="规格型号" align="center" prop="model" />
      <el-table-column label="执行标准" align="center" prop="executiveStandard" />
      <el-table-column label="抽样地点" align="center" prop="samplingSite" />
      <el-table-column label="抽样时间" align="center" prop="samplingDate" />
      <el-table-column label="承检机构" align="center" prop="orgName" />
      <el-table-column label="检验时间" align="center" prop="checkStartTime" />
      <el-table-column label="检验报告下载" align="center"  >
        <template #default="scope">
          <!-- <el-button type="primary" text @click="handleDownload(scope.row)">下载</el-button> -->
          <!-- <el-button type="succeext @click="handleGenerateReport(scope.row)">生成报告</el-button> -->
          <el-button type="primary" text @click="handleGenerateReport(scope.row)">检验报告下载</el-button>
        </template>
         </el-table-column>

    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <OrganizationQualificationForm ref="formRef" @success="getList" />

  <!-- 报告预览对话框 -->
  <el-dialog
    v-model="reportDialogVisible"
    title="检验报告预览"
    width="80%"
    :destroy-on-close="true"
  >
    <ReportTemplate ref="reportTemplateRef" :data="reportData" />
    <template #footer>
      <el-button @click="reportDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="exportPDF">导出PDF</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { OrganizationQualificationApi, OrganizationQualificationVO } from '@/api/qis/organizationqualification'
import OrganizationQualificationForm from './OrganizationQualificationForm.vue'
import { useMessage } from '@/hooks/web/useMessage'
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'
import ReportTemplate from './ReportTemplate.vue'
import { ref } from 'vue'
import { SampleInformationApi } from '@/api/qis/sampleinformation'
import { get } from 'axios'



/** 质检平台-承检资质 列表 */
defineOptions({ name: 'OrganizationQualification' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化


const arrayList = ref([])
const handleSelect = (row ) => {
  // console.log('删除指标要求', row)
  if(row.selected){
    arrayList.value.push(row.id)
    console.log(arrayList.value,'arrayList.value')
  }else {
    arrayList.value = arrayList.value.filter(item => item !== row.id)
    console.log(arrayList.value,'arrayList.value')
  }
}
const loading = ref(true) // 列表的加载中
const list = ref([{
  id: 0, // 主键id
  type: 1 ,// 证书类型: 0-CMA 1-CNAS 2-体系证书
  num: '10', // 证书编号
  licenceIssuingAuthority: '10' ,// 发证机关
  issueDate: '2024-12-12', // 发证时间
  expireTime: '2024-12-12' ,// 有效日期
  attachment: '', // 附件Url,多个用" ;"隔开 最多五个
  orgId: 10 // 机构id
}]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  type: 3,
 
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const reportDialogVisible = ref(false)
const reportTemplateRef = ref()
const reportData = ref({
  serialNo: '',
  reportTime: '',
  sampleNo: '',
  standard: '',
  samplingLocation: '',
  inspectionUnit: '',
  qrCodeUrl: '',
  items: [] as Array<{
    name: string
    unit: string
    requirement: string
    result: string
    judgment: string
    standard: string
    remark: string
  }>,
  conclusion: '',
  remark: ''
})

/** 查询列表 */
const getList = async () => {

queryParams.samplingStartDate =queryParams.samplingStartDate1 ?   queryParams.samplingStartDate1[0] :''
queryParams.samplingEndDate = queryParams.samplingStartDate1?  queryParams.samplingStartDate1[1] :''
queryParams.checkFilterStartTime = queryParams.checkStartTime1 ?  queryParams.checkStartTime1[0] :''
queryParams.checkFilterEndTime =  queryParams.checkStartTime1?  queryParams.checkStartTime1[1] :''

  loading.value = true
  try {
    const data = await SampleInformationApi.getSampleInformationPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  queryParams.samplingStartDate1 = undefined
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await OrganizationQualificationApi.deleteOrganizationQualification(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  if(total.value > 10000) return message.error('当前数据过大，请筛选数据后导出')
  try {
    if(arrayList.value.length > 0) {
      const idsArr = arrayList.value.join(';') 
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await SampleInformationApi.exportSampleInformation({ids:idsArr,...queryParams})
    download.excel(data, '质检平台-检查报告查询.xls')

    }else {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await SampleInformationApi.exportSampleInformation(queryParams)
    download.excel(data, '质检平台-检查报告查询.xls')
    }
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 生成报告操作 */
const handleGenerateReport =async (row: any) => {
  // 填充报告数据
  // reportData.value = {
  //   serialNo: row.id,  // 单据编号
  //   reportTime: new Date().toLocaleDateString(),  // 报告时间  
  //   sampleNo: row.sampleNo || '',  // 样品编号
  //   standard: row.standard || '',  // 样品名称
  //   a: row.standard || '',  // 规格型号
  //   samplingLocation: row.location || '', // 抽样地点
  //   inspectionUnit: row.orgName || '',  // 抽样时间
  //   b: row.orgName || '',  // 检验时间
  //   c: row.orgName || '',  // 承检单位
  //   d: row.orgName || '',  // 实验室名称
  //   qrCodeUrl: 'http://127.0.0.1:80/moduleHome', // 二维码链接
  //   items: [
  //     {
  //       name: '硬化时间',
  //       unit: 'min',
  //       requirement: '240~260',
  //       result: '145',
  //       judgment: '不合格',
  //       standard: 'GB/19139-2012',
  //       remark: ''
  //     },
  //     {
  //       name: '初始粘度',
  //       unit: 'Br',
  //       requirement: '≤30',
  //       result: '14',
  //       judgment: '合格',
  //       standard: 'GB/19139-2012',
  //       remark: ''
  //     }
  //   ],
  //   conclusion: '符合设计要求。',
  //   remark: '备注：实共用仪表要求测试时间低于下限30min以内合格。'
  // }

  console.log(row.id)
  const res =await  SampleInformationApi.getSampleInformation(row.id)
  console.log(res,'生成报告操作')
  reportData.value = res
  
  reportDialogVisible.value = true
}

/** 导出PDF */
const exportPDF = async () => {
  try {
    const element = reportTemplateRef.value?.reportRef
    if (!element) return

    const canvas = await html2canvas(element, {
      scale: 2,
      useCORS: true,
      logging: false
    })

    const imgData = canvas.toDataURL('image/jpeg', 1.0)
    const pdf = new jsPDF('p', 'mm', 'a4')
    const pdfWidth = pdf.internal.pageSize.getWidth()
    const pdfHeight = (canvas.height * pdfWidth) / canvas.width

    pdf.addImage(imgData, 'JPEG', 0, 0, pdfWidth, pdfHeight)
    pdf.save('检验报告.pdf')
    
    reportDialogVisible.value = false
    message.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    message.error('导出失败')
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})

onDeactivated(()=>{
  resetQuery()
})
</script>


<style lang="scss" scoped>

.table-btn{
  padding: 10px 50px;
}

:deep(.el-dialog__body) {
  max-height: 80vh;
  overflow-y: auto;
}
</style>